<?php
namespace org\crawlgenie\application\environment;
use \CGException;
use \CGConfig;


/**
 * Request class handles the abstraction of accessing GET, POST, COOKIE, or command line variables
 *
 * Tests: Manual
 *
 * @author Jinson
 */
class Request {


	/**
	 *  Identify if invoked from commandline
	 *	@return <boolean>	TRUE or FALSE
	*/
	public static function isCommandLineInvocation() {
		return (php_sapi_name() === 'cli' OR defined('STDIN'));
	}


    /**
     * Get the value of the request parameter
     *
     * @param <string> $name      Name of the request parameter
     * @param <string> $type      Type of predefined http variable to get the parameter from
     * @return <string>           Value of the requested variable
     */
    public static function getParam($name, $type = 'request') {
        $result = null;
		
		if(self::isCommandLineInvocation() || $type=='cli') {
			//rolling out our own because getopt requires that the arguments come in order, which is ridiculous
			global $argv;
			$working = $argv;
			//go through the array, if can find the exact match after the -|--, return the next element
			$c = count($working);
			for($i=1; $i <= $c; $i++) {
				if(preg_match('/^-{1,2}'. trim($name) .'$/', $working[$i])) {
					return $working[$i+1];
				}
			}
		} 
		
        if(!isset($_REQUEST[$name])) {
            return $result;
        } else {
            if(strtolower($type) == 'get') {
                $result = $_GET[$name];
            } elseif(strtolower($type) == 'post') {
                $result = $_POST[$name];
            } else {
                $result = $_REQUEST[$name];
            }
        }
        return $result;
    }


    
    /**
     * Obtain names of all parameters within GET, POST,
     * COOKIE, argv.
     *
     * @return  array   Keys of all parameters available
     * in the request's GET, POST and COOKIE, or argv variable
     */
    public static function getParamNames() {
		if(self::isCommandLineInvocation()) {
			global $argv;
			$working = $argv;
			$return = array();
			array_shift($working); //get rid of first element which is calling script.
			foreach($working as $element) {
				if(preg_match('/^-{1,2}(\w+)/', $element, $matches)) {
					$return[] = $matches[1];
				}
			}			
			return $return;
			
		} else {
			return array_keys($_REQUEST);
		}
    }



	
	
	
	    /**
     * Get the value of all the request parameters
     *
     * @param <string> $type      Type of predefined http variable to get the parameter from
     * @return <string>           Value of the requested variable
     */
    public static function getAllParams($type = 'request') {
	
		if(self::isCommandLineInvocation() || $type=='cli') {
			global $argv;
			$working = $argv;

			array_shift($working);			
			return print_r($working,true);
		} 
		
		if(strtolower($type) == 'get') {
			$result = print_r($_GET,true);
		} elseif(strtolower($type) == 'post') {
			$result = print_r($_POST,true);
		} else {
			$result = print_r($_REQUEST,true);
		}
		
		return $result;
    }
	
	
	
    public static function isGzipContent($content) {
        $firstTwoBytesInHex = bin2hex(substr($content, 0, 2));
        return ($firstTwoBytesInHex == '1f8b') ? TRUE : FALSE;
    }
	

    /**
     * Reconstructs a query string based on an associative array of parameters and values
     * Removes cookieId key and value beforehand.
     *
     * @param   <array>   $request        An associative array of query string key and value pairs
     * @param   <array>   $ignoredKeys    An array of keys for request params that we can ignore during reconstruction
     * @return  <array>   An array of query key/value pairs ready for reconstruction
     */
    private static function buildQuery($request, $ignoredKeys) {
        $keys = array_keys($request);
        $appCookieIdent = CGConfig::$cookieName;
        $newArray = array();

        foreach($keys as $key) {
            if($key != $appCookieIdent 
                && !in_array($key, $ignoredKeys)
                && stripos($key, ':') !== false) {

                $newArray[$key] = $keys[$key];
            }
        }
        return $newArray;
    }




    /**
     * Reconstructs a query string based on an associative array of parameters and values
     * Removes unwanted key/value pairs as well as cookieId key and value beforehand.
     *
     * @param   <array>   $request        An associative array of query string key and value pairs
     * @param   <array>   $ignoredKeys    An array of keys for request params that we can ignore during reconstruction
     * @return  <string>  A string ready to be appended to basename($_SERVER['PHP_SELF']).'?'
     */
    public static function generateURLQuery($request, $ignoredKeys) {
        $request = self::buildQuery($request, $ignoredKeys);
        return http_build_query($request);
    }



    /**
     * Reconstructs a query string based on an associative array of parameters and values
     * Removes unwanted key/value pairs as well as cookieId key and value beforehand.
     *
     * @param   <array>   $request        An associative array of query string key and value pairs
     * @param   <array>   $ignoredKeys    An array of keys for request params that we can ignore during reconstruction
     * @return  <string>  Previous page request query values as hidden form values ready to be appended to a form
     */
    public static function generateHiddenFormQuery($request, $ignoredKeys) {
        $request = self::buildQuery($request, $ignoredKeys);
        $result = '';

        foreach($request as $key => $value) {
            $result .= '<input type="hidden" name="'.$key.'" value="'.$value.'" />'."\r\n";
        }
        return $result;
    }

}
?>
